package com.pangolin.pangolinim.net;

import com.pangolin.pangolinim.utils.ConvertUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @desc 二进制协议编码类，组成C++结构体
 * @version 1.0
 */

public class BinaryWriteStream {
    private byte[] _bytes = null;
    private List<Byte> _list = new ArrayList<Byte>();

    public void writeInt(int a){
        byte[] tmp = ConvertUtil.intToBytes(a);
        for (int n = 0; n < tmp.length; ++n) {
            _list.add(tmp[n]);
        }
        return;
    }

    public void writeShort(short a){
        byte[] tmp = ConvertUtil.shortToBytes(a);
        for (int n = 0; n < tmp.length; ++n) {
            _list.add(tmp[n]);
        }
        return;
    }

    public void writeString(String a){
        byte[] tmp = a.getBytes();
        for (int n = 0; n < tmp.length; ++n) {
            _list.add(tmp[n]);
        }
        return;
    }

    public byte[] getData() {
        return _bytes;
    }

    public void flush() {

        int bytesLength = _list.size();
        _bytes = new byte[bytesLength];

        for (int k = 0; k < bytesLength; ++k) {
            Byte xb = _list.get(k);
            if (xb == null)
                _bytes[k] = 0;
            else
                _bytes[k] = (byte) xb;
            //System.out.println(k);
            //++i;
        }
    }
}
